package com.netted.operationassistant.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.mylhyl.superdialog.SuperDialog;
import com.netted.operationassistant.R;
import com.netted.operationassistant.constant.Constant;
import com.netted.operationassistant.entity.Port;
import com.netted.operationassistant.http.HttpRequest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 报修换机输入密码界面
 */
public class BXHJActivity extends BaseActivity {
    private TextView[] tvs;
    private String value = "";

    private TextView secondTv;
    private Handler secondHandler;
    private boolean isStop = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bxhj);

        initView();
    }

    private void initView(){
        tvs = new TextView[6];
        tvs[0] = (TextView)findViewById(R.id.bxhj_textview1);
        tvs[1] = (TextView)findViewById(R.id.bxhj_textview2);
        tvs[2] = (TextView)findViewById(R.id.bxhj_textview3);
        tvs[3] = (TextView)findViewById(R.id.bxhj_textview4);
        tvs[4] = (TextView)findViewById(R.id.bxhj_textview5);
        tvs[5] = (TextView)findViewById(R.id.bxhj_textview6);

        secondTv = (TextView)findViewById(R.id.bxhj_second);
        secondHandler = new Handler();
        new Thread(secondRunnable).start();
        playSound(this,R.raw.s6);
    }

    Runnable secondRunnable = new Runnable() {
        @Override
        public void run() {
            int i = 60;
            while(i >= 0 && !isStop){
                final int second = i;
                secondHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        secondTv.setText(second +"s");
                    }
                });
                i--;
                try{
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            if (i <= 0){
                exit(null);
            }
        }
    };

    public void del(View view){
        if (value != null && value.length() > 0){
            value = value.substring(0,value.length() - 1);
        }
        showNumber();
    }
    public void clean(View view){
        value = "";
        showNumber();
    }

    public void inputNumber(View view){
        Button b = (Button)view;
        value += b.getText();
        showNumber();
    }



    public void showNumber(){
        if (value != null){

            for(int i = 0; i < 6; i ++){
                if (i < value.length()){
                    tvs[i].setText("●");
                }else{
                    tvs[i].setText("");
                }

            }

            if (value.length() == 6){
                String catbinetId = sharedPreferencesHelper.getSharedPreference("id","") + "";
                if (catbinetId == null || "".equals(catbinetId)){
                    ToastUtils.showLong("丢失系统数据，请联系管理员！");
                }

                final ProgressDialog loadingDialog = ProgressDialog.show(this,"读取中", "正在验证信息", true, false);
                returnDeviceByRepair(catbinetId,value,loadingDialog);
                clean(null);
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }



    public void submit(View view){

    }


    public void returnDeviceByRepair(String catbinetId,String token,final ProgressDialog loadingDialog){


        Map<String,String > params = new HashMap<>();
        params.put("catbinetId",catbinetId+"");
        params.put("token", token);
        params.put("action", "归还故障平板");

        String url = Constant.HOST + "/ws/opt/returnDeviceByRepair";
        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                try {
                    if (StringUtils.isEmpty(response)){
                        showDialog("提示","返回数据异常",null);
                        return;
                    }else{
                        JSONObject resJson = JSONObject.parseObject(response);
                        if ("success".equals(resJson.getString("flag"))){
                            String data = resJson.getString("data");
                            if(!StringUtils.isEmpty(data)){
                                JSONObject dataJson = JSONObject.parseObject(data);
                                final String portStr= dataJson.getString("port");
                                Port p = getPortStatus(portStr);
                                if (p == null || p.getIsHas().equals("Y")){
                                    showDialog("提示", "仓内已有平板,无法再次放入", new SuperDialog.OnClickPositiveListener() {
                                        @Override
                                        public void onClick(View v) {
                                            BXHJActivity.this.finish();
                                        }
                                    });
                                    return;
                                }else{
                                    openPort(portStr);
                                    //showDialog("提示", "仓门已打开,请放入平板后关闭仓门", null);
                                    Thread.sleep(1000);
                                    serialValue = "";

                                    Intent intent = new Intent(BXHJActivity.this,ReturnTipsActivity.class);
                                    intent.putExtra("portStr",portStr);
                                    intent.putExtra("from","BXHJActivity");                                     startActivity(intent);
                                    startActivity(intent);
                                    BXHJActivity.this.finish();

                                    return;
                                }
                            }else{
                                showDialog("提示","返回数据异常",null);
                                return;
                            }
                        }else{
                            if ("错误的取机码".equals(resJson.getString("message"))){
                                playSound(BXHJActivity.this,R.raw.s7);
                            }
                            showDialog("提示",resJson.getString("message"),null);
                            return;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtils.e(e.getMessage());
                    showDialog("提示","获取数据异常",null);
                }


            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("错误提示",error.toString(),null);
            }
        });
    }





    @Override
    protected void onStop() {
        super.onStop();
        stopSound();
        isStop = true;
    }

    public void exit(View view){
        Intent intent = new Intent(this,MenuActivity.class);
        startActivity(intent);
        this.finish();
    }


    public void toReturnDevice(View view){
        Intent intent = new Intent(this,ReturnDeviceActivity.class);
        startActivity(intent);
        this.finish();
    }
}
